package com.bosssoft.boss_exam_web.Controller;


import com.bosssoft.boss_exam_core.common.Timer.CloseExamScheduler;
import com.bosssoft.boss_exam_core.exception.BusinessException;
import com.bosssoft.boss_exam_core.util.common.QrCodeUtil;
import com.bosssoft.boss_exam_db.entity.*;
import com.bosssoft.boss_exam_db.service.busines.*;
import com.bosssoft.boss_exam_db.validator.common.Phone;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@Validated
@RequestMapping("/test")
@Slf4j
@Api(value="测试接口Controller")
public class TestController {

    @Autowired
    private AdminService adminService;



    @PostMapping("/aa")
    @ResponseBody
    public Object test11() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Admin admin = adminService.selectByKey("1");
        return admin;
    }

    @GetMapping("/abc")
    @ResponseBody
    @ApiOperation(value="测试用接口", notes="测试用接口" ,httpMethod="POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name="phone", value="用户电话", dataType = "String", required=true, paramType="form")
    })
    public String get(@Phone @RequestParam String phone){
        Date date = new Date();
        long time = date.getTime();
        System.out.println(time);
        long l = System.currentTimeMillis();
        System.out.println(l);
        return "abc";
    }

    /**
     * 二维码
     * @param request
     * @param response
     */
    @RequestMapping("/qrcode11")
    public void qrcode(HttpServletRequest request, HttpServletResponse response) {
        StringBuffer url = request.getRequestURL();
        // 域名
        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();

        // 再加上请求链接
        String requestUrl = tempContextUrl + "/index";
        try {
            OutputStream os = response.getOutputStream();
            QrCodeUtil.encode(requestUrl, "/static/images/logo.png", os, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成二维码方法
     *
     * @param  content 要生成的内容
     * @param resp response对象
     * @throws Exception 抛出异常
     */
    @RequestMapping(value = "/qrcode")
    public void getQrcode(String content, HttpServletResponse resp) throws Exception {
        ServletOutputStream stream = null;
       /* Long qrid=Long.parseLong(content);
        Ticket ticket=ticketRepository.findByTicketId(qrid);
       if (ticket!=null) {*/
        try {
            stream = resp.getOutputStream();
            Map<EncodeHintType, Object> hints = new HashMap<>();
            //编码
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            //边框距
            hints.put(EncodeHintType.MARGIN, 0);
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bm = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 200, 200, hints);
            MatrixToImageWriter.writeToStream(bm, "png", stream);
        } catch (WriterException e) {
            e.getStackTrace();

        } finally {
            if (stream != null) {
                stream.flush();
                stream.close();
            }
        }
    }

    //打开生成二维码页面。
    @RequestMapping(value = "/open")
    public ModelAndView open1(String qrid1){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("index");
        return mv;
    }

    @RequestMapping(value = "createQrCode")
    public String abc(){
        String qrUrl = "https://mp.csdn.net/postedit/86678133";//扫描二维码跳转的链接
        String note = "我的二维码";//二维码下方展示的字
        File logoFile = new File("");//logo图片路径
        File codeFile = new File("");//生成后图片的输出地址
        return QrCodeUtil.drawLogoQRCode(logoFile, codeFile, qrUrl, note);
    }

    @RequestMapping(value = "/qq")
    public String crea(){
        String qrUrl = "https://mp.csdn.net/postedit/86678133";//扫描二维码跳转的链接
        String note = "我的二维码";//二维码下方展示的字
        File logoFile = new File("K:\\boss\\myProject\\resource\\boss_online_exam\\boss_exam_core\\src\\main\\resources\\static\\boss.jpg");//logo图片路径
        File codeFile = new File("K:\\boss\\myProject\\resource\\boss_online_exam\\boss_exam_core\\src\\main\\resources\\static\\e.jpg");//生成后图片的输出地址
        return  QrCodeUtil.drawLogoQRCode(logoFile, codeFile, qrUrl, note);
    }

    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private JobService jobService;


    @Autowired
    @Qualifier("transactionManager")
    private PlatformTransactionManager transactionManager;

    @GetMapping("/tx")
    public String txtest(){
        DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
        defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(defaultTransactionDefinition);

        Job job = new Job();
        job.setCompanyId("abc");
        SystemConfig systemConfig = new SystemConfig();
        systemConfig.setMainScope("efg");
        try{
//          两条处理都能够保存成功，但是第一个job处理保存成功都让它抛出异常，仅做测试
            if(jobService.saveNotNull(job)==1){
                throw new RuntimeException("保存job失败了");
            }
           if( systemConfigService.saveNotNull(systemConfig)!=1){
                throw new RuntimeException("保存config失败了");
            }
            transactionManager.commit(status);
        }catch (Exception e) {
            transactionManager.rollback(status);
            e.printStackTrace();
            log.error("save *** 异常");
        }
        return "";
    }

    @Autowired
    private CloseExamScheduler closeExamScheduler;

    /**
     * 測試定时
     */
    @RequestMapping("/time")
    @ResponseBody
    public Object test0001(){
        Date now = new Date();
        long time = now.getTime() + 1000 * 5;
        Date date = new Date(time);
        Exam exam1 = new Exam();
        exam1.setId("1");
        closeExamScheduler.startCron(date,exam1);
        return "aaa";
    }


    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;

    @GetMapping("/testMyTx")
    @ResponseBody
    public Object testMyTx(){
        DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
        defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(defaultTransactionDefinition);
        try{
            Menu menu = new Menu();
            menu.setName("mmmmmm");
            Role role = new Role();
            role.setName("rrrrrrr");
            menuService.saveNotNull(menu);
            System.out.println("中间");
            try{
                roleService.save(role);
                int a =  1/0;
            }catch (Exception e){
                throw new BusinessException("该事务操作失败");
            }
            transactionManager.commit(status);
        }catch (Exception e) {
            transactionManager.rollback(status);
            log.error("save *** 异常");
        }
        return "tx";
    }

    @GetMapping("/testMyTx2")
    @ResponseBody
    public Object testMyTx2(){
        try{
            Menu menu = new Menu();
            menu.setName("mmmmmm");
            Role role = new Role();
            role.setName("rrrrrrr");
            menuService.saveNotNull(menu);
            int a= 1/0;
        }catch (Exception e) {
            log.error("save *** 异常");
        }
        return "tx";
    }


    @Autowired
    private TestService testService;

    @GetMapping("/testMyTx3")
    @ResponseBody
    public Object testMyTx3(){
        try{
            Menu menu = new Menu();
            menu.setName("mmmmmm");
            Role role = new Role();
            role.setName("rrrrrrr");
            testService.modifyInsertTxFunction();
        }catch (Exception e) {
            log.error("save *** 异常");
        }
        return "tx";
    }
}
